/**
 * 
 */
package stormIO;
import java.io.*;
import java.security.Permission;
import java.security.Permissions;
import java.security.ProtectionDomain;

import  org.jawk.Awk;

import javax.xml.parsers.SAXParserFactory; 
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
/**
 * @author richard
 * cette classe permet d'utiliser jawk et de modifier valeur d'une balise system ENTITY sur la velru de la balise
 */
public class XmlEntity extends SecurityManager {
	
	  private boolean isExitAllowedFlag; 
	private String[] cmde;
	public void run() {
		 try {
			Awk.invoke(this.cmde);
		 } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Throwable x) {
			 System.out.println("Intercepted System.exit()");
		}

	}
	 public static void main(String args[])
	 
	  throws IOException, ClassNotFoundException {
		 String[] cmde=new String[1];
		 cmde[0]= "-h" ;
		Awk.invoke(cmde);
	  }
	 //  xe /tmp/test.xml /tmp/res.xml test1 /tmp/2.xml
	 public static void changeEntityValue(String entity, String newValue, String file, String filename) throws IOException, ClassNotFoundException{
		 String[] cmde=new String[2];
		 cmde[0]= "{if ($2==\""+ entity+ "\") { $4=\"\\\""+newValue+"\\\" >\";  print $0;}  else { print $0 ;} }" ;
		 cmde[1]= file ;
		//cmde[2]= "-o "+ file;
		 PrintStream crt = System.out;
		 PrintStream ps = new PrintStream(
                 new BufferedOutputStream(new FileOutputStream(
                 new File(filename))), true);
		 System.setOut(ps);
	//	 System.out.println("TEST  RES");
		 try{
		 XmlEntity thread = new XmlEntity();
		 thread.setCmde(cmde);
		
		 SecurityManager  oldsecu= System.getSecurityManager();
	
			 System.setSecurityManager(thread);
		 thread.run();
		 thread.setExitAllowed(true);
		 System.setSecurityManager(oldsecu);
		 }
		 catch(Exception E){
			 System.out.println("OK"  );
		 }
		 System.setOut(crt);
		 ps.close();
		 
		 //System.setSecurityManager(new java.lang.SecurityManager());
//		 Awk.invoke(cmde);
		 
	 }
	private void setCmde(String[] cmde) {
		// TODO Auto-generated method stub
		this.cmde = cmde;
		
	}
	
	
	/***
	 * Security manager
	 */
	public XmlEntity(){
		

	    super();
	 
	    Permissions perm = new Permissions();
	    perm.add(new RuntimePermission("createSecurityManager"));
	    isExitAllowedFlag = false;  
	  }
	 
	  public boolean isExitAllowed(){
	    return isExitAllowedFlag;	 
	  }
	 
	  @Override public void checkExit(int status) {
	    if(!isExitAllowed()) {
	      throw new SecurityException();
	    }
	    super.checkExit(status);
	  }
	 
	  public void setExitAllowed(boolean f) {
	    isExitAllowedFlag = f; 	 
	  }
	  public void checkPermission(Permission p) { 
		
	} 
	
}
